package com.heba.greenmulu.user;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.user.UserDiaryObject;
import com.heba.config.CommonConfig;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.DateHelper;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.CommonUtils;
import com.heba.utils.GlideUtil;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户日记收藏页面
 * Created by jason on 2020/3/13.
 */
public class UserDiaryFavoriteActivity extends BaseActivity {

    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private List<UserDiaryObject> list;
    private TextView alertLB;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recyclerview);
        initTopbar();
        findViewById();
        initView();
        getDiaryListData();
    }

    @Override
    protected void findViewById() {
        refreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recyclerView);
        alertLB = findViewById(R.id.alertLB);
        alertLB.setText(R.string.no_fav_diary);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.mine_diary_collect));

        list = new ArrayList<>();

        recycleAdapter = new QuickAdapter<UserDiaryObject>(list) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.recycle_item_user_diary;
            }

            @Override
            public void convert(VH holder, UserDiaryObject data, int position) {
                GlideUtil.loadImageWithPlaceHolderID(UserDiaryFavoriteActivity.this, data.getIcon(), holder.getView(R.id.iv_avatar), R.drawable.icon_head_portrait);
                holder.setText(R.id.tv_name, data.getAccount());
                holder.setText(R.id.tv_time, DateHelper.transferDateString(UserDiaryFavoriteActivity.this, data.getTimeCreated()));
                holder.setText(R.id.tv_content, CommonUtils.getDecodeText(data.getContent()));
                holder.getView(R.id.iv_photo).setVisibility(View.INVISIBLE);
                if (data.getImageUrl() != null && !data.getImageUrl().isEmpty()) {
                    holder.getView(R.id.iv_photo).setVisibility(View.VISIBLE);
                    GlideUtil.loadImageWithDefaultPlaceHolder(UserDiaryFavoriteActivity.this, data.getImageUrl(), holder.getView(R.id.iv_photo));
                }

                /**
                 * 跳转日记详情页面
                 */
                holder.itemView.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putInt(CommonConfig.TYPE, 1);
                    bundle.putString(CommonConfig.DIARY_ID, data.getDiaryID());
                    openActivity(UserDiaryListActivity.class, bundle);
                });

            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            Page = 1;
            isRefreshFromTop = true;
            getDiaryListData();
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            Page++;
            isRefreshFromTop = false;
            getDiaryListData();
        });
    }

    /**
     * 获取日记收藏列表
     */
    private void getDiaryListData() {
        if (firstRefresh) {
            firstRefresh = false;
            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", PerPage);
        client.get(Cfg.BaseUrl + "/User/DiaryFavorite", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);

                        /**
                         * 下拉刷新处理
                         */
                        if (isRefreshFromTop) {
                            isRefreshFromTop = false;
                            refreshLayout.setNoMoreData(false);
                            list.clear();
                        }

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<UserDiaryObject> diaryObjects = new Gson().fromJson(array.toString(), new TypeToken<List<UserDiaryObject>>() {
                                }.getType());
                                list.addAll(list.size(), diaryObjects);
                                alertLB.setVisibility(View.GONE);
                            } else {
                                //无数据
                                refreshLayout.finishLoadMoreWithNoMoreData();
                                alertLB.setVisibility(View.VISIBLE);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //刷新数据
                        recycleAdapter.notifyDataSetChanged();
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);
                    }

                });
    }
}
